# @Time    : 2019/1/13 11:28
# @Author  : xufqing
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import BasePermission
from collections import defaultdict
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.db.models.query import QuerySet

class CommonPagination(PageNumberPagination):
    '''
    分页设置
    '''
    page_size = 10
    page_size_query_param = 'size'


class RbacPermission(BasePermission):
    '''
    自定义权限
    '''
    def get_user(self, request):
        return request.user

    def get_permission_from_role(self, request):
        if request.user:
            try:
                perms_dict = defaultdict(set)
                perms = request.user.roles.values(
                    'permissions__menus__path',
                    'permissions__method',
                ).distinct()
                for item in perms:
                    #获取当前用户的权限，并转换为GET/POST/PUT等
                    method = item['permissions__method'].split('_')[-1]
                    if method == 'ALL':
                        perms_dict[item['permissions__menus__path']].add('GET')
                        perms_dict[item['permissions__menus__path']].add('POST')
                        perms_dict[item['permissions__menus__path']].add('PUT')
                        perms_dict[item['permissions__menus__path']].add('DELETE')
                    else:
                        perms_dict[item['permissions__menus__path']].add(method)
                return perms_dict
            except AttributeError:
                return None
        return None

    def has_permission(self, request, view):
        request_perms = self.get_permission_from_role(request)
        if request_perms:
            request_url = request._request.path_info.split('/')[2] #截取request的路径
            SAFEMETHOD = ('HEAD', 'OPTIONS')
            #管理员有所有权限
            if 'ADMIN' in request_perms[None]:
                return True
            elif request._request.method in request_perms[request_url]:
                return True
            elif request._request.method in SAFEMETHOD:
                return True

class TreeSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    label = serializers.CharField(max_length=20,source='name')
    pid = serializers.PrimaryKeyRelatedField(read_only=True)

class TreeAPIView(APIView):
    '''
    自定义树结构View
    '''
    authentication_classes = (JSONWebTokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    queryset = None

    def get_queryset(self):
        assert self.queryset is not None, (
            "'%s' should either include a `queryset` attribute, "
            "or override the `get_queryset()` method."
            % self.__class__.__name__
        )
        queryset = self.queryset
        if isinstance(queryset, QuerySet):
            queryset = queryset.all()
        return queryset

    def get(self, request):
        data = self.get_queryset()
        serializer = TreeSerializer(data, many=True)
        tree_dict = {}
        tree_data = []
        for item in serializer.data:
            tree_dict[item['id']] = item
        for i in tree_dict:
            tree_dict[i]['children'] = []
            if tree_dict[i]['pid']:
                pid = tree_dict[i]['pid']
                parent = tree_dict[pid]
                parent['children'].append(tree_dict[i])
            else:
                tree_data.append(tree_dict[i])
        return Response(tree_data)